<template>
  <div>
    <!-- 配镜 -->
    <el-form
      v-for="(item, index) in tableData"
      :key="index"
      :model="item"
      :rules="allRules[index]"
      :ref="(el) => addSchemeRef(el)"
    >
      <el-card class="optical" @dblclick="handleEdit">
        <template #header>
          <div class="head w-full flex justify-between items-center px-2">
            <div class="w-[55%] flex justify-between items-center">
              <el-tag v-if="opticianEditStatus == 1">
                {{ item.name }}
              </el-tag>
              <el-form-item v-else prop="name" style="width: 10rem">
                <el-input
                  size="small"
                  v-model="item.name"
                  class="input_style"
                  clearable
                  placeholder="请输入方案名称"
                />
              </el-form-item>
              <div class="title text-[1rem] font-bold">{{ themeTitle }}</div>
            </div>
            <div class="btn w-[10rem] flex justify-end">
              <el-button
                type="danger"
                link
                @click="handleRemove(index)"
                v-if="opticianEditStatus == 2"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
              <el-button
                type="primary"
                link
                title="打印"
                @click="handlePrint(index)"
                v-if="opticianEditStatus == 1"
              >
                <el-icon><Printer /></el-icon>
              </el-button>
            </div>
          </div>
        </template>
        <table class="optical_table">
          <tr>
            <th>姓名</th>
            <td :colspan="2">
              <span v-if="opticianEditStatus == 1">{{ item.cusName }}</span>
              <el-form-item prop="cusName" v-else>
                <el-input
                  v-model="item.cusName"
                  class="input_style"
                  clearable
                  placeholder="请输入姓名"
                />
              </el-form-item>
            </td>
            <th>联系方式</th>
            <td :colspan="2">
              <span v-if="opticianEditStatus == 1">{{ item.cusPhone }}</span>
              <el-form-item prop="cusPhone" v-else>
                <el-input
                  v-model="item.cusPhone"
                  class="input_style"
                  clearable
                  placeholder="请输入联系方式"
                />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th></th>
            <th>球镜</th>
            <th>柱镜</th>
            <th>光轴</th>
            <th>矫正视力</th>
            <th>视近加</th>
          </tr>
          <tr>
            <th>右 (R)</th>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.rightQ }}</span>
              <el-form-item prop="rightQ" v-else>
                <el-input
                  v-model="item.rightQ"
                  class="input_style"
                  clearable
                  placeholder="请输入右眼球镜"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.rightZ }}</span>
              <el-form-item prop="rightZ" v-else>
                <el-input
                  v-model="item.rightZ"
                  class="input_style"
                  clearable
                  placeholder="请输入右眼柱镜"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.rightG }}</span>
              <el-form-item prop="rightG" v-else>
                <el-input
                  v-model="item.rightG"
                  class="input_style"
                  clearable
                  placeholder="请输入右眼光轴"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.rightJ }}</span>
              <el-form-item prop="rightJ" v-else>
                <el-input
                  v-model="item.rightJ"
                  class="input_style"
                  clearable
                  placeholder="请输入右眼矫正视力"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.rightS }}</span>
              <el-form-item prop="rightS" v-else>
                <el-input
                  v-model="item.rightS"
                  class="input_style"
                  clearable
                  placeholder="请输入右眼视近加"
                />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th>左 (L)</th>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.leftQ }}</span>
              <el-form-item prop="leftQ" v-else>
                <el-input
                  v-model="item.leftQ"
                  class="input_style"
                  clearable
                  placeholder="请输入左眼球镜"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.leftZ }}</span>
              <el-form-item prop="leftZ" v-else>
                <el-input
                  v-model="item.leftZ"
                  class="input_style"
                  clearable
                  placeholder="请输入左眼柱镜"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.leftG }}</span>
              <el-form-item prop="leftG" v-else>
                <el-input
                  v-model="item.leftG"
                  class="input_style"
                  clearable
                  placeholder="请输入左眼光轴"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.leftJ }}</span>
              <el-form-item prop="leftJ" v-else>
                <el-input
                  v-model="item.leftJ"
                  class="input_style"
                  clearable
                  placeholder="请输入左眼矫正视力"
                />
              </el-form-item>
            </td>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.leftS }}</span>
              <el-form-item prop="leftS" v-else>
                <el-input
                  v-model="item.leftS"
                  class="input_style"
                  clearable
                  placeholder="请输入左眼视近加"
                />
              </el-form-item>
            </td>
          </tr>
          <!-- <tr>
            <td :colspan="6"></td>
          </tr> -->
          <tr>
            <th>瞳距</th>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.pupil }}</span>
              <el-form-item prop="pupil" v-else>
                <el-input
                  v-model="item.pupil"
                  class="input_style"
                  clearable
                  placeholder="请输入瞳距"
                />
              </el-form-item>
            </td>
            <th>近用</th>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.collect }}</span>
              <el-form-item prop="collect" v-else>
                <el-input
                  v-model="item.collect"
                  class="input_style"
                  clearable
                  placeholder="请输入近用"
                />
              </el-form-item>
            </td>
            <th>验光</th>
            <td>
              <span v-if="opticianEditStatus == 1">{{ item.optometry }}</span>
              <el-form-item prop="optometry" v-else>
                <el-input
                  v-model="item.optometry"
                  class="input_style"
                  clearable
                  placeholder="请输入验光"
                />
              </el-form-item>
            </td>
          </tr>
          <!-- <tr>
            <td :colspan="6"></td>
          </tr> -->
          <tr>
            <th></th>
            <th>品名</th>
            <th>单位</th>
            <th>数量</th>
            <th>单价</th>
            <th>小计</th>
          </tr>
          <tr>
            <th>镜架</th>
            <td :colspan="5">
              <span v-if="opticianEditStatus == 1">{{ item.eyeglass }}</span>
              <el-form-item prop="eyeglass" v-else>
                <el-input
                  v-model="item.eyeglass"
                  class="input_style"
                  clearable
                  placeholder="请输入镜架"
                />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th>镜片</th>
            <td :colspan="5">
              <span v-if="opticianEditStatus == 1">{{ item.lens }}</span>
              <el-form-item prop="lens" v-else>
                <el-input
                  v-model="item.lens"
                  class="input_style"
                  clearable
                  placeholder="请输入镜片"
                />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th>备注</th>
            <td :colspan="5">
              <span v-if="opticianEditStatus == 1">{{ item.remark }}</span>
              <el-form-item prop="remark" v-else>
                <el-input
                  v-model="item.remark"
                  class="input_style"
                  clearable
                  placeholder="请输入备注"
                />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <th :rowspan="2">经手人</th>
            <td :rowspan="2">
              <span v-if="opticianEditStatus == 1">{{ item.worker }}</span>
              <el-form-item prop="worker" v-else>
                <el-input
                  v-model="item.worker"
                  class="input_style"
                  clearable
                  placeholder="请输入经手人"
                />
              </el-form-item>
            </td>
            <th :rowspan="2">总计</th>
            <td :colspan="3" class="text-left">
              <span v-if="opticianEditStatus == 1">{{ item.amount }}</span>
              <el-form-item prop="amount" v-else>
                <el-input-number
                  v-model="item.amount"
                  class="input_style"
                  clearable
                  placeholder="请输入总计金额"
                  :precision="2"
                  :min="0"
                />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td :colspan="3" class="text-left">
              {{ item.amountInWords }}
            </td>
          </tr>
        </table>
      </el-card>
    </el-form>

    <el-card class="mt-1" v-if="tableData?.length < 3">
      <el-empty :description="tableData?.length == 0 ? '暂无数据' : ' '">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-empty>
    </el-card>

    <div class="fixed bottom-1 right-3" v-if="route.name != 'home_page'">
      <el-button v-if="opticianEditStatus == 2" @click="handleCancelEdit"
        >取消编辑</el-button
      >
      <el-button
        type="primary"
        v-if="opticianEditStatus == 1 && tableData && tableData.length > 0"
        @click="handleEdit"
        >编辑</el-button
      >
      <el-button
        type="primary"
        v-if="opticianEditStatus == 2"
        @click="handleSubmit"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watchEffect } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { cloneDeep } from "lodash";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import { numberToChineseMoney } from "@/utils/init.js";
import { handleApiResponse } from "@/utils/request.js";
import { CreateGlassesInfo } from "../../../../../../../wailsjs/go/api/ReportApi";

onMounted(() => {});

const route = useRoute();
const userStore = useUserStore();
const { checkDetailForm, themeTitle, opticianEditStatus } =
  storeToRefs(userStore);

const emit = defineEmits(["handleRefreshData"]);
const props = defineProps({
  checklistId: {
    type: Number,
    default: 0,
  },
});

const dataForm = ref({});

const opticalForm = ref({
  name: "新的配镜方案",
  cusName: "",
  cusPhone: "",
  rightQ: "",
  rightZ: "",
  rightG: "",
  rightJ: "",
  rightS: "",
  leftQ: "",
  leftZ: "",
  leftG: "",
  leftJ: "",
  leftS: "",
  pupil: "",
  collect: "",
  optometry: "",
  eyeglass: "",
  lens: "",
  remark: "",
  worker: "",
  amount: null,
  amountInWords: "",
});
const tableData = ref([]);

const rules = ref({
  name: [
    {
      required: true,
      message: "请输入方案名称",
    },
  ],
  cusPhone: [
    {
      required: true,
      message: "请输入联系方式",
    },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入联系方式"));
        } else if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的联系方式"));
        } else {
          callback();
        }
      },
    },
  ],
  rightQ: [
    {
      required: true,
      message: "请输入右眼球镜",
    },
  ],
  rightZ: [
    {
      required: true,
      message: "请输入右眼柱镜",
    },
  ],
  rightG: [
    {
      required: true,
      message: "请输入右眼光轴",
    },
  ],
  rightJ: [
    {
      required: true,
      message: "请输入右眼矫正视力",
    },
  ],
  rightS: [
    {
      required: true,
      message: "请输入右眼视力加",
    },
  ],
  leftQ: [
    {
      required: true,
      message: "请输入左眼球镜",
    },
  ],
  leftZ: [
    {
      required: true,
      message: "请输入左眼柱镜",
    },
  ],
  leftG: [
    {
      required: true,
      message: "请输入左眼光轴",
    },
  ],
  leftJ: [
    {
      required: true,
      message: "请输入左眼矫正视力",
    },
  ],
  leftS: [
    {
      required: true,
      message: "请输入左眼视力加",
    },
  ],
  pupil: [
    {
      required: true,
      message: "请输入瞳距",
    },
  ],
  collect: [
    {
      required: true,
      message: "请输入近用",
    },
  ],
  optometry: [
    {
      required: true,
      message: "请输入验光",
    },
  ],
  eyeglass: [
    {
      required: true,
      message: "请输入镜架",
    },
  ],
  lens: [
    {
      required: true,
      message: "请输入镜片",
    },
  ],
  remark: [
    {
      required: false,
      message: "请输入备注",
    },
  ],
  worker: [
    {
      required: true,
      message: "请输入经手人",
    },
  ],
  amount: [
    {
      required: true,
      message: "请输入金额",
    },
    {
      pattern: /^[0-9]+.?[0-9]*$/,
    },
  ],
});

const allRules = computed(() => {
  const rulesArray = [];
  for (let i = 0; i < tableData.value.length; i++) {
    rulesArray.push(rules);
  }
  return rulesArray;
});

const schemeRefs = ref([]);
const addSchemeRef = (el) => {
  if (el && !schemeRefs.value.includes(el)) {
    schemeRefs.value.push(el);
  }
};

const handleAdd = () => {
  tableData.value.push(cloneDeep(opticalForm.value));
};

// 提交
const handleSubmit = async () => {
  let form = cloneDeep(dataForm.value);
  if (props.checklistId != 0 && props.checklistId != -1) {
    form.checklistId = props.checklistId;
  }
  form.glassesAdvice = JSON.stringify(tableData.value);

  handleApiResponse(() => CreateGlassesInfo(form)).then((res) => {
    if (res.code == 0) {
      ElMessage.success("保存成功");
      userStore.updateOpticianEditStatus(1);
      emit("handleRefreshData");
    }
  });

  return;
  // 验证表单
  const results = await Promise.all(
    schemeRefs.value.map(
      (item) => new Promise((resolve) => item.validate(resolve))
    )
  );

  if (results.every((valid) => valid)) {
    // 检查所有验证结果
    ElMessage.success("提交成功");
    userStore.updateOpticianEditStatus(1);
  } else {
    ElMessage.warning("请将信息填写完整");
  }
};

// 删除单个方案
const handleRemove = (index) => {
  ElMessageBox.confirm("确定删除该方案吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    tableData.value.splice(index, 1);
  });
};

// 打印
const handlePrint = (index) => {
  const printContent = document.createElement("div");
  const originalContent = document
    .querySelectorAll(".optical")
    [index].cloneNode(true);

  // 清除操作按钮
  originalContent.querySelector(".btn").remove();

  // 添加打印样式
  const printStyle = document.createElement("style");
  printStyle.innerHTML = `
    @media print {
      body * { visibility: hidden; }
      .print-content, .print-content * { visibility: visible; }
      .print-content { 
        position: absolute; 
        left: 0; 
        top: 0; 
        width: 100%; 
        box-shadow: none; 
      }
        .head {
      display: flex !important;
      justify-content: space-between !important;
      align-items: center !important;
      padding: 0 0.5rem !important;
      width: 100% !important;
    }
      .head > div {
      width: 55% !important;
      display: flex !important;
       justify-content: space-between !important;
    }
       .head .title{
        font-size:1.2rem !important;
        font-weight:bold !important;
       }
    
      .optical_table {
        border-collapse: collapse;
        width: 100%;
        border: 1px solid #333!important; // 强制显示边框
       }
      .optical_table th, .optical_table td {
        height: 2rem !important;
        border: 1px solid #333 !important; // 强制显示边框
        border-collapse: collapse !important;
        text-align: center  !important;
      }
    }
  `;

  printContent.appendChild(printStyle);
  printContent.appendChild(originalContent);
  printContent.className = "print-content";

  // 创建临时打印窗口
  const printWindow = window.open("", "_blank");
  printWindow.document.body.appendChild(printContent);
  printWindow.print();
  setTimeout(() => printWindow.close(), 500);
};

// 点击编辑按钮
const handleEdit = () => {
  userStore.updateOpticianEditStatus(2);
};
// 取消编辑
const handleCancelEdit = () => {
  userStore.updateOpticianEditStatus(1);
  emit("handleRefreshData");
};

// 监听刷新数据
let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_optician", (e) => {
    if (e.data.opticianType === 1) {
      // ElMessage.warning("取消编辑");
      emit("handleRefreshData");
      userStore.updateOpticianEditStatus(1);
    } else if (e.data.opticianType === 2) {
      // 提交
      handleSubmit();
    }
  });
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
  userStore.updateOpticianEditStatus(1);
});

// 接收数据
let cleanup2;
onMounted(() => {
  cleanup2 = watchStorage("scheme_data", (e) => {
    // console.log(e.data);
    dataForm.value = e.data || {};
    tableData.value = JSON.parse(e.data.glassesAdvice || "[]");
  });
  return () => cleanup2();
});

onBeforeUnmount(() => {
  cleanup2();
});

// 换算大写总价
watchEffect(() => {
  tableData.value.forEach((item) => {
    item.amountInWords = numberToChineseMoney(item.amount);
  });
});
</script>

<style scoped lang="scss">
.optical {
  @apply w-full h-full mt-2;

  .optical_table {
    border-collapse: collapse;
    @apply w-full h-full text-[0.8rem] text-center;

    tr {
      @apply w-full h-[1.5rem];
      th,
      td {
        border: 0.08rem solid #ebeef5;
        padding: 0.3rem 0.2rem;
        box-sizing: border-box;
        width: 16.5%;
      }
      th {
        background-color: #f5f7fa;
      }
      td:hover {
        @apply cursor-pointer text-[var(--theme-color)] bg-[#f5f7fa];
      }
    }
  }
}

.el-form-item {
  @apply w-full mb-0;
}
.input_style {
  @apply w-full;
}

// @media print {
//   .optical_table {
//     th,
//     td {
//       border: 1px solid #333 !important; // 强制显示边框
//       border-collapse: collapse !important;

//       // 恢复具体尺寸定义
//       border-width: 1px 0 0 1px !important;
//       &:first-child {
//         border-left-width: 0 !important;
//       }
//       &:last-child {
//         border-right-width: 1px !important;
//       }
//     }

//     // 添加表格外围边框
//     border: 2px solid #000 !important;
//   }
// }
</style>